package com.arges.web.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.arges.web.common.Constant;
import com.arges.web.common.GsonUtils;
import com.arges.web.common.JXLHandler;
import com.arges.web.domain.bean.BloodBean;
import com.arges.web.domain.bean.FunBean;
import com.arges.web.domain.bean.PatBean;
import com.arges.web.domain.bean.TreatBean;
import com.arges.web.domain.pojo.Blood;
import com.arges.web.domain.pojo.Fun;
import com.arges.web.domain.pojo.Pat;
import com.arges.web.domain.pojo.Pthlgy;
import com.arges.web.domain.pojo.Treat;
import com.arges.web.page.PageInfo;
import com.arges.web.page.WebUtils;
import com.arges.web.service.BloodManager;
import com.arges.web.service.FunManager;
import com.arges.web.service.PatManager;
import com.arges.web.service.PthlgyManager;
import com.arges.web.service.TreatManager;

/**
 * doctor控制层
 * 
 * @author zxj
 *
 */
@Controller
@Scope("prototype")
@RequestMapping("/pat")
public class PatController
{

	private Logger LOGGER = LoggerFactory.getLogger(PatController.class);

	@Autowired
	private PatManager patManager;

	@Autowired
	private PthlgyManager pthlgyManager;

	@Autowired
	private TreatManager treatManager;

	@Autowired
	private FunManager funManager;

	@Autowired
	private BloodManager bloodManager;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getPagePat.do")
	public String getPagePat(HttpServletRequest request, ModelMap map)
	{

		PageInfo<PatBean> pageInfo = null;
		String mrn = request.getParameter("search_mrn");
		if (!StringUtils.isNotBlank(mrn))
		{
			mrn = "";
		}
		String pageString = request.getParameter("PageInfo");
		if (StringUtils.isNotBlank(pageString))
		{
			pageInfo = GsonUtils.stringToObject(pageString, PageInfo.class);
		}
		else
		{
			pageInfo = new PageInfo<PatBean>();
		}

		try
		{
			PageInfo<Pat> pojopInfo = WebUtils.beanToPojoPage(pageInfo, Pat.class);
			pageInfo = patManager.getPagePat(pojopInfo, mrn);
		}
		catch (Exception e)
		{
			System.out.println("getPagePat is error. e=" + e);
		}
		map.put("chaxun", mrn);
		map.put("patBeanList", pageInfo.getResult());
		pageInfo.setResult(null);
		map.put("patPageInfo", GsonUtils.objectToJson(pageInfo));
		return "pat/pat";
	}

	@RequestMapping(value = "/saveOrUpdate.do")
	@ResponseBody
	public String saveOrUpdate(HttpServletRequest request, PatBean patBean)
	{
		String result = Constant.SUCCESS;

		try
		{
			if (patBean.getMrn().equals("系统自动生成"))
			{
				PatBean lastPatBean = patManager.getLastPatBean();
				Pat pat = new Pat();
				BeanUtils.copyProperties(patBean, pat);
				if (null == lastPatBean)
				{
					lastPatBean = new PatBean();
					lastPatBean.setMrn("100000000");
				}
				Long mrnLong = Long.valueOf(lastPatBean.getMrn());
				pat.setMrn(String.valueOf(++mrnLong));
				pat.setDate(new Date());
				Pthlgy pthlgy = new Pthlgy();
				pthlgy.setMrn(pat.getMrn());
				patManager.save(pat);
				pthlgyManager.save(pthlgy);
				result = pat.getMrn();
			}
			else
			{

				Pat pat = new Pat();
				BeanUtils.copyProperties(patBean, pat);
				PatBean oldPat = patManager.getPatByMrn(pat.getMrn());
				pat.setDate(oldPat.getDate());
				pat.setId(oldPat.getId());
				patManager.update(pat);
				result = pat.getMrn();
			}
		}
		catch (Exception e)
		{
			System.out.println("saveOrUpdate is error,error is" + e);
			result = Constant.ERROR;
		}

		return result;
	}

	/**
	 * 根据病历号获取患者信息
	 * 
	 * @param mrn
	 * @return
	 */
	@RequestMapping(value = "/getPatByMrn.do")
	@ResponseBody
	public PatBean getPatByMrn(HttpServletRequest request)
	{
		String mrn = request.getParameter("mrn");
		PatBean patBean = null;
		try
		{
			patBean = patManager.getPatByMrn(mrn);
		}
		catch (Exception e)
		{
			System.out.println("getPatByMrn is error,error is" + e);
			patBean = null;
		}
		return patBean;
	}

	/**
	 * 删除、批量删除用户
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/deleteByIds.do")
	@ResponseBody
	public String deleteByIds(HttpServletRequest request)
	{
		String result = Constant.SUCCESS;
		String ids = request.getParameter("ids");
		try
		{
			patManager.deleteByIds(ids);
			pthlgyManager.deleteByIds(ids);
		}
		catch (Exception e)
		{
			System.out.println("delete pat ByIds is error,error is" + e);
			result = Constant.ERROR;
		}
		return result;
	}

	/**
	 * 根据病历号精确查找病人基本、病理信息
	 * 
	 * @param mrn
	 * @return
	 */
	@RequestMapping(value = "/getPatInfoByMrn.do")
	@ResponseBody
	public PatBean getPatInfoByMrn(HttpServletRequest request)
	{
		String mrn = request.getParameter("mrn");

		PatBean patBean = pthlgyManager.getPthlgyByMrn(mrn);
		String egfr = patBean.getEgfr();
		String smoke = patBean.getSmoke();
		if (StringUtils.isNotBlank(egfr))
		{
			if (egfr.equals("1"))
			{
				patBean.setEgfr("突变");
			}
			else
			{
				patBean.setEgfr("未突变");
			}
		}
		if (StringUtils.isNotBlank(smoke))
		{
			if (smoke.equals("1"))
			{
				patBean.setSmoke("有");
			}
			else
			{
				patBean.setSmoke("无");
			}
		}

		return patBean;
	}

	/**
	 * 根据病历号精确查找病人诊断治疗分页
	 * 
	 * @param mrn
	 * @return
	 */
	@RequestMapping(value = "/getPatInfoTreatPage.do")
	@ResponseBody
	public PageInfo<TreatBean> getPatInfoTreatPage(HttpServletRequest request)
	{
		String mrn = request.getParameter("mrn");
		PageInfo<TreatBean> treatPageInfo = new PageInfo<TreatBean>();
		PageInfo<Treat> treatPojopInfo = WebUtils.beanToPojoPage(treatPageInfo, Treat.class);
		treatPageInfo = treatManager.getPageTreat(treatPojopInfo, mrn, "", "");

		return treatPageInfo;
	}

	/**
	 * 根据病历号精确查找病人随访记录分页
	 * 
	 * @param mrn
	 * @return
	 */
	@RequestMapping(value = "/getPatInfoFunPage.do")
	@ResponseBody
	public PageInfo<FunBean> getPatInfoFunPage(HttpServletRequest request)
	{
		String mrn = request.getParameter("mrn");
		PageInfo<FunBean> funPageInfo = new PageInfo<FunBean>();
		PageInfo<Fun> funPojopInfo = WebUtils.beanToPojoPage(funPageInfo, Fun.class);
		funPageInfo = funManager.getPageFun(funPojopInfo, mrn, "", "");

		return funPageInfo;
	}

	/**
	 * 根据病历号精确查找病人血液标本分页
	 * 
	 * @param mrn
	 * @return
	 */
	@RequestMapping(value = "/getPatInfoBloodPage.do")
	@ResponseBody
	public PageInfo<BloodBean> getPatInfoBloodPage(HttpServletRequest request)
	{
		String mrn = request.getParameter("mrn");
		PageInfo<BloodBean> bloodPageInfo = new PageInfo<BloodBean>();
		PageInfo<Blood> bloodPojopInfo = WebUtils.beanToPojoPage(bloodPageInfo, Blood.class);
		bloodPageInfo = bloodManager.getPageBlood(bloodPojopInfo, mrn, "", "");

		return bloodPageInfo;
	}

	/**
	 * 统计信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getPatCount.do")
	@ResponseBody
	public List<PatBean> getPatCount(HttpServletRequest request)
	{
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		if (StringUtils.isBlank(startTime))
		{
			startTime = "";
		}
		if (StringUtils.isBlank(endTime))
		{
			endTime = "";
		}
		List<PatBean> patList = new ArrayList<PatBean>();
		patList = patManager.getPatBeanList(startTime, endTime);
		for (PatBean patBean : patList)
		{
			// patBean.setAddr("1");
			// patBean.setId_card("1");
			// patBean.setPhone("1");
			// patBean.setName("1");
			// patBean.setIsCure("1");
			// patBean.setDate(new Date());
		}
		return patList;
	}

	/**
	 * 患者信息导出
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/exportPat.do")
	@ResponseBody
	public String exportPat(HttpServletRequest request, HttpServletResponse response)
	{
		String result = Constant.SUCCESS;
		WritableWorkbook w = null;
		try
		{

			OutputStream out = response.getOutputStream();
			response.reset();
			String fileName = new String("患者信息表".getBytes("gb2312"), "ISO-8859-1") + ".xls";
			response.setHeader("content-disposition", "attachment;filename=" + fileName);
			response.setContentType("application/msexcel");
			w = Workbook.createWorkbook(out);
			WritableSheet sheet = w.createSheet("sheet1", 10);
			String[] heads = { "病历号", "姓名", "性别", "身份证号", "电话", "家庭住址", "肿瘤部位", "分化程度", "TNM分期", "病理类型", "EGFR检测",
					"吸烟史", "其他病史" };
			sheet = JXLHandler.setSheetStyle(sheet, "患者信息", heads);
			List<PatBean> list = patManager.getPatBeanList("", "");

			for (int i = 0; i < list.size(); i++)
			{
				Label mrn = new Label(0, i + 2, list.get(i).getMrn(), JXLHandler.getTableStyle());
				Label name = new Label(1, i + 2, list.get(i).getName(), JXLHandler.getTableStyle());
				Label sex = new Label(2, i + 2, list.get(i).getSex(), JXLHandler.getTableStyle());
				Label idCard = new Label(3, i + 2, list.get(i).getId_card(), JXLHandler.getTableStyle());
				Label phone = new Label(3, i + 2, list.get(i).getPhone(), JXLHandler.getTableStyle());
				Label addr = new Label(4, i + 2, list.get(i).getAddr(), JXLHandler.getTableStyle());
				Label zlbw = new Label(5, i + 2, list.get(i).getTumor_site(), JXLHandler.getTableStyle());
				Label fhcd = new Label(6, i + 2, list.get(i).getDffrnttn(), JXLHandler.getTableStyle());
				Label tnm = new Label(7, i + 2, list.get(i).getTnm(), JXLHandler.getTableStyle());
				Label bllx = new Label(8, i + 2, list.get(i).getPathology(), JXLHandler.getTableStyle());
				Label egfr = new Label(9, i + 2, list.get(i).getEgfr(), JXLHandler.getTableStyle());
				Label smoke = new Label(10, i + 2, list.get(i).getSmoke(), JXLHandler.getTableStyle());
				Label qtbs = new Label(11, i + 2, list.get(i).getMedical_history(), JXLHandler.getTableStyle());
				sheet.addCell(mrn);
				sheet.addCell(name);
				sheet.addCell(sex);
				sheet.addCell(idCard);
				sheet.addCell(phone);
				sheet.addCell(addr);
				sheet.addCell(zlbw);
				sheet.addCell(fhcd);
				sheet.addCell(tnm);
				sheet.addCell(bllx);
				sheet.addCell(egfr);
				sheet.addCell(smoke);
				sheet.addCell(qtbs);
			}
			w.write();
		}
		catch (Exception e)
		{
			result = Constant.ERROR;
		}
		finally
		{
			JXLHandler.close(null, w);
		}

		return result;
	}

}
